package cn.stylefeng.guns.sys.modular.dbServicelist.service.impl;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.dataQualityCheck.entity.QualityCheck;
import cn.stylefeng.guns.sys.modular.dbServicelist.entity.DbServicelist;
import cn.stylefeng.guns.sys.modular.dbServicelist.entity.Exchange;
import cn.stylefeng.guns.sys.modular.dbServicelist.mapper.DbServicelistMapper;
import cn.stylefeng.guns.sys.modular.dbServicelist.model.params.DbServicelistParam;
import cn.stylefeng.guns.sys.modular.dbServicelist.model.result.DbServicelistResult;
import cn.stylefeng.guns.sys.modular.dbServicelist.service.DbServicelistService;
import cn.stylefeng.guns.sys.modular.dbservicedetails.entity.DbServicedetails;
import cn.stylefeng.guns.sys.modular.dbservicedetails.model.params.DbServicedetailsParam;
import cn.stylefeng.guns.sys.modular.dbservicedetails.service.DbServicedetailsService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.swagger.models.auth.In;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.net.InetAddress;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 目录服务  服务实现类
 * </p>
 *
 * @author zhaoyiheng
 * @since 2020-08-19
 */
@Service
public class DbServicelistServiceImpl extends ServiceImpl<DbServicelistMapper, DbServicelist> implements DbServicelistService {
    @Autowired
    private DbServicedetailsService dbServicedetailsService;


    @Override
    public void add(DbServicelistParam param, LoginUser user) {
        DbServicelist entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(DbServicelistParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(DbServicelistParam param) {
        DbServicelist oldEntity = getOldEntity(param);
        DbServicelist newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public DbServicelistResult findBySpec(DbServicelistParam param) {
        return null;
    }

    @Override
    public List<DbServicelistResult> findListBySpec(DbServicelistParam param) {
        return this.baseMapper.customList(param);
    }

    @Override
    public LayuiPageInfo findPageBySpec(DbServicelistParam param) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
        Page pageContext = getPageContext();
        param.setUserId(LoginContextHolder.getContext().getUserId());
        if (StringUtils.isEmpty(param.getState())) {
            param.setState("2");
        }

        IPage page = this.baseMapper.customPageList(pageContext, param);
        List<DbServicelistResult> records = page.getRecords();
        for (DbServicelistResult record : records) {
            long time = simpleDateFormat.parse(record.getEffectiveTime()).getTime();
            record.setEffectiveTime(time + "");
        }
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public void upDataTime(DbServicelistParam param) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
        DbServicelist dbServicelist = baseMapper.selectById(param.getId());
        Date parse = simpleDateFormat.parse(dbServicelist.getEffectiveTime());
        Calendar cd = Calendar.getInstance();
        cd.setTime(parse);
        //增加时间
        if ("3".equals(param.getEffectiveTime())) {
            cd.add(Calendar.MONTH, 3);

        } else if ("6".equals(param.getEffectiveTime())) {
            cd.add(Calendar.MONTH, 6);
        } else if ("9".equals(param.getEffectiveTime())) {
            cd.add(Calendar.YEAR, 1000);
        }
        dbServicelist.setEffectiveTime(simpleDateFormat.format(cd.getTime()));
        dbServicelist.setUpdatedTime(new Date());
        dbServicelist.setUpdatedBy(LoginContextHolder.getContext().getUser().getUsername());
        baseMapper.updateById(dbServicelist);
    }

    @Override
    public LayuiPageInfo findPageBySpecTime(DbServicelistParam param) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制
        Page pageContext = getPageContext();
        param.setUserId(LoginContextHolder.getContext().getUserId());
        IPage page = this.baseMapper.customPageListTime(pageContext, param);
        List<DbServicelistResult> records = page.getRecords();
        for (DbServicelistResult record : records) {
            long time = simpleDateFormat.parse(record.getEffectiveTime()).getTime();
            record.setEffectiveTime(time + "");
        }
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public void offShelf(DbServicelistParam dbServicelistParam) throws ParseException {
//
    }

    @Override
    public void active(DbServicelistParam dbServicelistParam, LoginUser user) throws ParseException {

    }

    @Override
    public LayuiPageInfo findServicePageBySpec(DbServicelistParam param) throws ParseException {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageServiceList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo queryApply(DbServicelistParam param) throws ParseException {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.queryApplyList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public String testConnectServer(DbServicelistParam param) {
        //测试连接服务器返回数据clear
        String clear = "";
        String ipAddr = param.getDbUrl();

        try {
            InetAddress address = InetAddress.getByName(ipAddr);
            if (address instanceof java.net.Inet4Address) {
                System.out.println(ipAddr + " is ipv4 address");
            } else if (address instanceof java.net.Inet6Address) {
                System.out.println(ipAddr + " is ipv6 address");
            } else {
                System.out.println(ipAddr + " is unrecongized");
            }
            //使用isReachable(int timeout)判断是否能够ping通
            if (address.isReachable(3000)) {
                clear = "1";
            } else {
                clear = "2";
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        //数据库返回值
        String returnString = "";
        //声明Connection对象
        Connection con;
        //数据库配置时的用户名
        String user = param.getUsername();
        //数据库配置时的密码
        String password = param.getPassword();
        String driver = "";
        String url = "";
        if (param.getDbType().equals("1")) {
            //驱动程序名
            driver = "com.mysql.cj.jdbc.Driver";
            //URL指向要访问的数据库名mydata
            url = "jdbc:mysql://" + param.getDbUrl() + ":" + param.getDbNumber() + "/" + param.getDbName() + "?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=CONVERT_TO_NULL&useSSL=false&serverTimezone=CTT";
        } else if (param.getDbType().equals("2")) {
            //驱动程序名
            driver = "oracle.jdbc.OracleDriver";
            //URL指向要访问的数据库名mydata
            url = "jdbc:oracle:thin:@" + param.getDbUrl() + ":" + param.getDbNumber() + "/" + param.getDbName();
        }
        //遍历查询结果集
        try {
            //加载驱动程序
            Class.forName(driver);
            //1.getConnection()方法，连接MySQL数据库！！
            con = DriverManager.getConnection(url, user, password);
            if (!con.isClosed()) {
                returnString = "1";
            }
            con.close();
        } catch (ClassNotFoundException e) {
            //数据库驱动类异常处理
            returnString = "2";
//            e.printStackTrace();
        } catch (SQLException e) {
            //数据库连接失败异常处理
            e.printStackTrace();
            returnString = "2";
        } catch (Exception e) {
            e.printStackTrace();
            returnString = "2";
        } finally {
        }
        return clear + "," + returnString;
    }

    @Override
    public List<Exchange> searchExchangeList(Exchange exchange) {
        return this.baseMapper.queryExchangeListInfo(exchange);
    }

    @Override
    public DbServicelistResult queryDbServiceListInfo(Integer id) {
        return this.baseMapper.queryDbServiceListById(id);
    }

    @Override
    public LayuiPageInfo queryServiceListByParam(DbServicelistParam param) throws ParseException {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.queryServiceList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }


    private Serializable getKey(DbServicelistParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private DbServicelist getOldEntity(DbServicelistParam param) {
        return this.getById(getKey(param));
    }

    private DbServicelist getEntity(DbServicelistParam param) {
        DbServicelist entity = new DbServicelist();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
